Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

  1. 'A' -> 1
  2. 'B' -> 2
  3. ...
  4. 'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,

Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

Solution:

  1. public class Solution {
  2. public int numDecodings(String s) {
  3. if (s == null || s.length() == 0)
  4. return 0;
  5. if (s.charAt(0) == '0')
  6. return 0;
  7. int n = s.length();
  8. int[] dp = new int[n + 1];
  9. dp[0] = 1; dp[1] = 1;
  10. for (int i = 2; i <= n; i++) {
  11. int count = 0;
  12. if (s.charAt(i - 1) > '0')
  13. count = dp[i - 1];
  14. if (s.charAt(i - 2) == '1' || (s.charAt(i - 2) == '2' && s.charAt(i - 1) <= '6'))
  15. count += dp[i - 2];
  16. dp[i] = count;
  17. }
  18. return dp[n];
  19. }
  20. }